import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:ez_ic_led/home/my_home.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import 'tool/assets.dart';

Future<void> main() async {
  /// 捕获所有未捕获的 Dart 异常
  LogManager.initFireBase(runMain: () async {
    BluetoothManager.instance.requestPermissions();
    await _loadThumbImage();
    initRealm();
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]).then((_) {
      runApp(MyApp());
    });
  });
}

void initRealm() {
  // // 创建不同模型的 RealmManager 实例
  // peripheralManager = RealmManager<DSPeripheral>(realm);
}

// 异步加载图片并解码为 ui.Image
ui.Image? _thumbImage;
Future<void> _loadThumbImage() async {
  final ByteData data = await rootBundle.load(assets.slider_p); // 读取图片资源
  final List<int> bytes = data.buffer.asUint8List();
  _thumbImage = await decodeImageFromList(Uint8List.fromList(bytes));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'EZ IC LED',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // 设置全局 AppBar 主题
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.transparent, // AppBar 背景颜色
          titleTextStyle: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), // AppBar 标题文本颜色
        ),

        // 设置全局文本颜色
        textTheme: const TextTheme(
          bodySmall: TextStyle(color: Colors.white), // 小号文本颜色
          bodyMedium: TextStyle(color: Colors.white), // 中号文本颜色
          bodyLarge: TextStyle(color: Colors.white), // 大号文本颜色
        ),

        ///全局slider设置
        sliderTheme: SliderThemeData(
          trackHeight: 5,
          activeTrackColor: Colors.white, // 滑动过的颜色
          inactiveTrackColor: const ui.Color.fromARGB(255, 118, 107, 107), // 未滑动部分的颜色
          // activeTrackColor: Colors.transparent, // 滑动过的颜色
          // inactiveTrackColor: Colors.transparent, // 未滑动部分的颜色
          thumbColor: Colors.white, // 滑块的颜色
          overlayColor: Colors.red.withOpacity(0.2), // 滑块按下时的颜色
          activeTickMarkColor: Colors.transparent, // 隐藏刻度线
          inactiveTickMarkColor: Colors.transparent, // 隐藏刻度线
          // thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 8.0), // 自定义滑块的形状和大小
          overlayShape: const RoundSliderOverlayShape(overlayRadius: 10.0), // 设置圆点到两端的间距为 0 以减小间距
          trackShape: GradientSliderTrackShape(
              gradient: LinearGradient(
                  colors: [Color_left, Color_right], // 渐变色
                  stops: [0.0, 1.0],
                  begin: Alignment.bottomLeft,
                  end: Alignment.topRight)),
          thumbShape: CustomSliderThumbShape(_thumbImage), // Set custom thumb shape

          // thumbIcon: Image.asset('assets/slider_thumb.png'), // 自定义滑点图片
        ),

        highlightColor: Colors.blue, // 按钮等组件点击时的高亮颜色
        splashColor: Colors.blue, // 点击时的水波纹颜色
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),

        useMaterial3: true,
      ),
      home: PopScope(
          //禁止屏幕边缘滑动，返回app
          child: const MyHome(),
          canPop: false,
          onPopInvokedWithResult: (didPop, result) {
            print("---------->  ${didPop},${result}");
          }),
      builder: EasyLoading.init(),
    );
  }
}

class GradientSliderTrackShape extends SliderTrackShape {
  final LinearGradient gradient;
  GradientSliderTrackShape({required this.gradient});

  @override
  void paint(
    PaintingContext context, // 绘制的上下文，提供绘制功能，用于在画布上绘制轨道和滑块
    Offset offset, // 滑块的偏移量，指示了滑块在屏幕上的位置
    {
    required RenderBox parentBox, // 父组件的渲染框，包含了父容器的布局信息和尺寸
    required SliderThemeData sliderTheme, // 包含滑块主题的配置信息，控制着滑块的外观、颜色、尺寸等
    required Animation<double> enableAnimation, // 用于表示滑块启用状态的动画（例如启用/禁用的渐变效果）
    required Offset thumbCenter, // 滑块的中心点坐标，表示滑块在轨道中的位置
    Offset? secondaryOffset, // 用于双滑块模式的第二个滑块的偏移量（如果是单滑块，这个值为 `null`）
    bool? isEnabled, // 滑块是否启用，控制是否可以与用户交互
    bool? isDiscrete, // 滑块是否为离散值（即是否有固定的滑动步长）
    required TextDirection textDirection, // 文本方向（用于决定组件的绘制方向，左到右或右到左）
  }) {
    Offset customOffset = offset.translate(0.0, 0.0); // 水平偏移 10.0 单位

    final Rect trackRect = getPreferredRect(
      parentBox: parentBox,
      sliderTheme: sliderTheme,
      offset: customOffset,
      isEnabled: isEnabled ?? true,
      isDiscrete: isDiscrete ?? false,
    );

    // 使用 RRect 给轨道加圆角
    final RRect roundedTrackRect = RRect.fromRectAndRadius(
      trackRect,
      const Radius.circular(8), // 设置圆角半径
    );

    final Paint trackPaint = Paint()..shader = gradient.createShader(trackRect);

    final Paint inactiveTrackPaint = Paint()..color = Colors.black; // 未滑动部分为黑色

    // 绘制未滑动部分的黑色轨道
    context.canvas.drawRRect(roundedTrackRect, inactiveTrackPaint);

    // 绘制已滑动部分的渐变轨道
    double thumbPos = thumbCenter.dx - trackRect.left;
    final Rect activeTrackRect = Rect.fromLTRB(trackRect.left, trackRect.top, thumbPos, trackRect.bottom);
    context.canvas.drawRRect(
      RRect.fromRectAndRadius(activeTrackRect, const Radius.circular(8)),
      trackPaint,
    );
  }

  @override
  Rect getPreferredRect({
    required RenderBox parentBox,
    Offset offset = Offset.zero,
    required SliderThemeData sliderTheme,
    bool isEnabled = true,
    bool isDiscrete = false,
  }) {
    // 确保导轨水平居中
    double trackWidth = parentBox.size.width - sliderTheme.trackHeight!;
    double trackTop = (parentBox.size.height - sliderTheme.trackHeight!) / 2;
    print('=======>123 ${parentBox.size.width}, ${parentBox.size.height},  ${sliderTheme.trackHeight}');

    return Rect.fromLTWH(
      offset.dx + (parentBox.size.width - trackWidth) / 2, // 居中水平位置
      offset.dy + trackTop, // 垂直居中
      trackWidth, // 轨道宽度
      sliderTheme.trackHeight!, // 轨道高度
    );
  }
}

class WheelEffect extends StatefulWidget {
  @override
  _WheelEffectState createState() => _WheelEffectState();
}

class _WheelEffectState extends State<WheelEffect> with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(); // 无限循环滚动动画
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<ui.Image>(
      future: _loadImage(assets.scroll), // 加载轮胎纹理图片
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {
          return AnimatedBuilder(
            animation: _controller,
            builder: (context, child) {
              return CustomPaint(
                painter: WheelPainter(snapshot.data!, _controller.value),
                size: const Size(200, 200), // 轮胎大小
              );
            },
          );
        } else {
          return const CircularProgressIndicator(); // 图片未加载完成时显示加载指示器
        }
      },
    );
  }

  // 加载图片资源
  Future<ui.Image> _loadImage(String asset) async {
    final data = await DefaultAssetBundle.of(context).load(asset);
    final codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    final frame = await codec.getNextFrame();
    return frame.image;
  }
}

class WheelPainter extends CustomPainter {
  final ui.Image image; // 轮胎纹理图片
  final double progress; // 动画进度（0 ~ 1）
  WheelPainter(this.image, this.progress);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    final rect = Rect.fromLTWH(0, 0, size.width, size.height);

    // 滚动进度计算偏移
    final dy = size.height * progress;

    // 创建图片纹理的 Shader
    paint.shader = ImageShader(
      image,
      TileMode.repeated,
      TileMode.mirror,
      Float64List.fromList([
        1, 0, 1, 0, // 第一行
        0, 1, dy, 0, // 第二行
        0, 0, 1, 0, // 第三行（这里是平移值，dy 计算了根据进度的偏移）
        0, 0, 0, 1, // 第四行
      ]),
    );

    // 绘制带有动态滚动效果的轮胎纹理
    canvas.drawRect(rect, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true; // 每帧都需要重新绘制
  }
}

// 自定义的 SliderComponentShape，用图片绘制 thumb
class CustomSliderThumbShape extends SliderComponentShape {
  final ui.Image? image;

  CustomSliderThumbShape(this.image);

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    // 设置 thumb 的大小（例如：40x40 像素）
    return Size(25.0, 25.0);
  }

  @override
  void paint(
    PaintingContext context,
    ui.Offset center, {
    required Animation<double> activationAnimation,
    required Animation<double> enableAnimation,
    required bool isDiscrete,
    required TextPainter labelPainter,
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required ui.TextDirection textDirection,
    required double value,
    required double textScaleFactor,
    required ui.Size sizeWithOverflow,
  }) {
    if (image != null) {
      // 确保图片已加载
      final paint = Paint();
      // 定义你想要的图像的尺寸，例如 40x40
      double targetWidth = 25.0;
      double targetHeight = 25.0;

      // 计算图像的左上角坐标，确保图像在 center 位置居中
      double xOffset = center.dx - targetWidth / 2;
      double yOffset = center.dy - targetHeight / 2;

      // 定义绘制的矩形区域
      Rect targetRect = Rect.fromLTWH(xOffset, yOffset + 1, targetWidth, targetHeight);

      // 使用 drawImageRect 方法绘制图像，指定目标矩形区域
      context.canvas.drawImageRect(
          image!, Rect.fromLTWH(0, 0, image!.width.toDouble(), image!.height.toDouble()), targetRect, paint);
    }
  }
}
